//
//  RecordSupplyDetailController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/23.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import ObjectMapper
class RecordSupplyDetailController: BaseViewController {
    fileprivate var _tableView: UITableView!
    fileprivate var fillRecordModel:FillRecordModel?
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView(frame: CGRect.zero, style: .grouped)
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
            _tableView.showsVerticalScrollIndicator = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            _tableView.separatorStyle = .none
            
            _tableView.register(TextViewCell.self, forCellReuseIdentifier: "\(TextViewCell.self)")
            
           // _tableView.register(RecordTimelineCell.self, forCellReuseIdentifier: "\(RecordTimelineCell.self)")
            _tableView.register(UINib.init(nibName: "FillRecordCell", bundle: nil), forCellReuseIdentifier: "fill")
            
            return _tableView
        }
    }
    
    fileprivate var applyTimeLabel: UILabel = {
        let label = UILabel()
        label.text = "申请时间:"
        label.font = wwFont_Regular(15)
        return label
    }()
    
    fileprivate var applyTimeDetailLabel: UILabel = {
        let label = UILabel()
        label.font = wwFont_Regular(15)
        return label
    }()
    fileprivate lazy var stateLabel:UILabel = {
        let label = UILabel()
        label.font = wwFont_Medium(17)
        label.textAlignment = .center
        label.textColor = UIColor.red
        return label
    }()
    
    //传入变量。     签到记录cell对应的model
    var recordApplyModel: RecordSupplyApply?
    
    //本地变量。  签到记录（就是那个时间线）
    var recordModels = [RecordModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
        if self.recordApplyModel != nil {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy年MM月dd日"
            let dateString = formatter.string(from: self.recordApplyModel!.signedDate!)
            self.title = dateString
        }
        
        
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "点击", style: .done, target: self, action: #selector(doButtonAction))
        
        self.setupViews()
        self.getData()
        self.updateViews()
        
       // self.showLoadingView()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    func setupViews() {
        let headerView = UIView()
        self.view.addSubview(headerView)
        headerView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(64)
            make.left.right.equalTo(self.view)
            make.height.equalTo(60)
        }
        
        headerView.addSubview(self.applyTimeLabel)
        self.applyTimeLabel.snp.makeConstraints { (make) in
            make.left.equalTo(headerView).offset(20)
            make.top.equalTo(headerView).offset(10)
            make.height.equalTo(19)
            make.width.equalTo(65)
        }
        headerView.addSubview(self.applyTimeDetailLabel)
        self.applyTimeDetailLabel.snp.makeConstraints { (make) in
        make.left.equalTo(self.applyTimeLabel.snp.right).offset(10)
            make.top.bottom.equalTo(self.applyTimeLabel)
            make.right.equalTo(headerView).offset(-15)
        }
        headerView.addSubview(stateLabel)
        self.stateLabel.snp.makeConstraints { (make) in
        make.top.equalTo(self.applyTimeLabel.snp.bottom).offset(5)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 100, height: 21))
        }
        
        if let flow = self.recordApplyModel?.workFlowState {
            var flowText = ""
            switch flow {
            case .unCommited:
                flowText = "未提交"
            case .approvalPending:
                flowText = "待审批"
            case .inTheFlow:
                flowText = "流转中"
            case .finished:
                flowText = "已完结"
            case .stop:
                flowText = "被中止"
            case .returned:
                flowText = "被退回"
            case .exception:
                flowText = "异常"
            }
            self.stateLabel.text = flowText
        }
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.top.equalTo(headerView.snp.bottom)
        }
    }
    
    func doButtonAction() {
        
    }
    func updateViews() {
        if let model = self.recordApplyModel ,let date = model.createDate{
            let dateString = dateTimeToString(date: date)
            self.applyTimeDetailLabel.text = dateString
        }
        
        self.tableView.reloadData()
    }
    
    func getData() {
        self.setupFillRecordDetailData {
            
        }
    }
    
    fileprivate func setupFillRecordDetailData(_ completion:@escaping () -> Void){
        guard let itemModel = self.recordApplyModel else {
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else {
            return
        }
        guard let applyId = itemModel.applyId else {
            return
        }
    LCAPiSubManager.request(.GetEntityOrderByOrderID(AccountId: accountId, orderID: applyId)) { (result) in
        if case let .success(response) = result {
            guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                return
            }
           
            guard let formDic : NSDictionary  = jsonString["Form"] as? NSDictionary else{
                return
            }
           self.fillRecordModel = Mapper<FillRecordModel>().map(JSONObject: formDic)
            self.tableView.reloadData()
            completion()
        }
     }
    }
}

extension RecordSupplyDetailController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return [45, 200][indexPath.section]
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            
            let cell : FillRecordCell = tableView.dequeueReusableCell(withIdentifier: "fill") as! FillRecordCell
            
            if (self.fillRecordModel != nil){
           cell.setupCellDataWithModel(self.fillRecordModel!)
            }
            
            return cell
            
        }
        else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(TextViewCell.self)", for: indexPath) as! TextViewCell
            
            cell.detailTextView.isEditable = false
            if let reasonString = self.fillRecordModel?.SupplementReason {
                cell.detailTextView.text = reasonString
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
//        if section == 1 {
            let view = UIView()
            
            let label = UILabel()
            label.font = wwFont_Medium(17)
            label.text = ["", "缺工原因"][section]
            view.addSubview(label)
            label.snp.makeConstraints { (make) in
                make.left.equalTo(view).offset(20)
                make.top.equalTo(view).offset(10)
                make.bottom.equalTo(view).offset(-10)
            }
            return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        if section == 1 {
            return 40
//        }
//        return 0
    }
}
